package cn.meng.base.utils;

import cn.meng.base.vo.BusinessException;

import java.util.UUID;

/**
 * 20位的Pk生成器，由于大量场景会用到此类生成主键，所以采用单例模式，节省资源
 * 懒汉式，考虑多线程的场景
 * @author 万梦辉
 */
public class GenerateUtil {

    private static GenerateUtil util;

    private GenerateUtil() {}

    public static GenerateUtil getInstance() {
        if(null == util) {
            synchronized (GenerateUtil.class) {
                if(null == util) {
                    util = new GenerateUtil();
                }
            }
        }
        return util;
    }

    /**
     * 生成20位主键
     * @return
     * @throws BusinessException
     */
    public String generate() throws BusinessException {
        String value = UUID.randomUUID().toString();
        String result = "";
        for(String tempStr : value.split("-")) {
            result = result + tempStr;
        }
        result = result.toUpperCase();
        if(result.length() >= 20) {
            result = result.substring(0,20);
        }else {
            throw new BusinessException(500,"主键生成异常");
        }
        return result;
    }

}
